package k.aicodeback.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import k.aicodeback.ai.enms.CodeGenTypeEnum;
import k.aicodeback.ai.model.HtmlCodeResult;
import k.aicodeback.ai.model.MultiFileCodeResult;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class CodeFileSaver {

    // 文件保存根目录
    private static final String FILE_SAVE_ROOT_DIR = System.getProperty("user.dir") + "/tmp/code_output";

    /**
     * 保存 HtmlCodeResult
     */
    public static File saveHtmlCodeResult(HtmlCodeResult result) {
        String dirPath=buildUniqueDir(CodeGenTypeEnum.HTML.getValue());
        writeToFile(dirPath,"index.html",result.getHtmlCode());
        return new File(dirPath);
    }

    /**
     * 保存 MultiFileCodeResult
     */
    public static File saveMultiFileCodeResult(MultiFileCodeResult result) {
        String dirPath=buildUniqueDir(CodeGenTypeEnum.MULTI_FILE.getValue());
        writeToFile(dirPath,"index.html",result.getHtmlCode());
        writeToFile(dirPath,"script.js",result.getJsCode());
        writeToFile(dirPath,"style.css",result.getCssCode());
        return new File(dirPath);
    }

    /**
     * 构建唯一目录路径：tmp/code_output/bizType_雪花ID
     */
    private static String buildUniqueDir(String bizType) {
        String dirName = StrUtil.format("{}_{}", bizType, IdUtil.getSnowflakeNextId());
        String url=FILE_SAVE_ROOT_DIR+File.separator+dirName;
        FileUtil.mkdir(url);
        return url;
    }

    /**
     * 写入单个文件
     */
    private static void writeToFile(String dirPath, String filename, String content) {
        String file=dirPath+File.separator+filename;
        FileUtil.writeString(content,file,StandardCharsets.UTF_8);
    }
}
